package com.key.puzzlemodel.cutterman

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.key.puzzlemodel.R
import com.key.puzzlemodel.databinding.ActivityPreviewBinding
import com.key.puzzlemodel.databinding.RecyclerCutterManItemBinding
import com.key.puzzlemodel.databinding.RecyclerCutterManShowBinding
import com.key.puzzlemodel.dialog.DialogUtil
import com.key.puzzlemodel.mvvm.BaseMVVMActivity
import com.key.puzzlemodel.util.BitmapUtil
import com.key.puzzlemodel.util.PuzzleAppManager

/**
 * 宫格拼图显示界面
 */
class PreviewActivity : BaseMVVMActivity<ActivityPreviewBinding, PreMVVMViewModel>() {

    override val layoutId: Int?
        get() = R.layout.activity_preview


    //列表横向排列的数量
    var horizontalPicNumber = 3

    var verticalPicNumber = 3

    //照片列表
    var bitmapResultList = ArrayList<String>()


    override fun initView(savedInstanceState: Bundle?) {
        //添加activity管理
        PuzzleAppManager.getInstance().addActivity(this)

        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE

        initTopView()

//        bitmapList = intent.getParcelableArrayListExtra<Bitmap>("bitmapList") as ArrayList<Bitmap>
        horizontalPicNumber = intent.getIntExtra("horizontalPicNumber", 0)
        verticalPicNumber = intent.getIntExtra("verticalPicNumber", 0)

        initRecyclerItem()
        initRecyclerShow()

        mVM.saveResult.observe(this) {
            CutterManConfig.bitmaps = ArrayList()
            DialogUtil.closeDialog()

            if (it) {
                Log.e(
                    "保存照片",
                    "保存路径：$verticalPicNumber ---  $horizontalPicNumber  ${bitmapResultList.size}"
                )
//                var intent = Intent()
//                intent.putExtra(PuzzleConfig.EDIT_RESULT, bitmapResultList)
//                intent.putExtra(PuzzleConfig.HOR_PIC_NUMBER, horizontalPicNumber)
//                intent.putExtra(PuzzleConfig.VER_PIC_NUMBER, verticalPicNumber)
//                setResult(Activity.RESULT_OK, intent)

                setResult(Activity.RESULT_OK, Intent().apply {
                    putExtra(com.key.puzzlemodel.config.PuzzleConfig.EDIT_RESULT, bitmapResultList)
                    putExtra(com.key.puzzlemodel.config.PuzzleConfig.HOR_PIC_NUMBER, horizontalPicNumber)
                    putExtra(com.key.puzzlemodel.config.PuzzleConfig.VER_PIC_NUMBER, verticalPicNumber)
                })
                this.finish()
                //AppManager.getInstance().finishActivity(PreviewActivity::class.java)
            } else {
                Toast.makeText(this, "导出失败，请重试", Toast.LENGTH_SHORT).show()
            }
        }
    }


    private fun initTopView() {
        findViewById<TextView>(R.id.txt_cutter_man_top_title).text =
            getString(R.string.string_preview)

        findViewById<ImageView>(R.id.image_cutter_man_return).setOnClickListener {
            onBackPressed()
        }

        //保存
        val txtSave = findViewById<TextView>(R.id.txt_cutter_man_top_title_right)
        txtSave.visibility = View.VISIBLE
        txtSave.text = getString(R.string.str_puzzle_export)
        txtSave.setOnClickListener {
            DialogUtil.showLoading(this, "正在导出中...")
            saveBitmap()
        }

    }

    private fun initRecyclerItem() {
        if (horizontalPicNumber == 0) {
            return
        }


        val layoutManager = GridLayoutManager(this, 5)
        layoutManager.orientation = RecyclerView.VERTICAL

        mVDB.recyclerItem.layoutManager = layoutManager
        mVDB.recyclerItem.adapter = itemAdapter(this, CutterManConfig.bitmaps)
        mVDB.recyclerItem.addItemDecoration(SpaceItemDecoration(horizontalPicNumber))
    }

    private fun initRecyclerShow() {
        if (horizontalPicNumber == 0) {
            return
        }

        val layoutManager = GridLayoutManager(this, horizontalPicNumber)
        layoutManager.orientation = RecyclerView.VERTICAL

        mVDB.recyclerShow.layoutManager = layoutManager
        mVDB.recyclerShow.adapter = ShowAdapter(this, CutterManConfig.bitmaps)
        mVDB.recyclerShow.addItemDecoration(SpaceItemDecoration(horizontalPicNumber))
    }


    var saveNumber = 0;


    private fun saveBitmap() {
        if (saveNumber == CutterManConfig.bitmaps.size) {
            mVM.saveResult.value = true
            return
        }

        //循环保存数据
        BitmapUtil.savePuzzleBitmap(this, CutterManConfig.bitmaps[saveNumber]) { state, imagePath ->
            if (state) {
                saveNumber++
                bitmapResultList.add(imagePath)
            }
            saveBitmap()
        }
    }


    class SpaceItemDecoration(val horizontalPicNumber: Int = 3) : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            outRect.left = 6
            outRect.right = 6
            outRect.top = 6
            outRect.bottom = 6
            //每行左边距设为0
//            if (parent.getChildLayoutPosition(view!!) % horizontalPicNumber == 0) {
//                outRect.left = 0
//            }
        }
    }


    class itemAdapter(var context: Context, var itemList: ArrayList<Bitmap>) :
        RecyclerView.Adapter<itemAdapter.ViewHolder>() {


        inner class ViewHolder(val binding: RecyclerCutterManItemBinding) :
            RecyclerView.ViewHolder(binding.root) {
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder(
                DataBindingUtil.inflate(
                    LayoutInflater.from(context),
                    R.layout.recycler_cutter_man_item,
                    parent,
                    false
                )
            )
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.binding.imgItem.setImageBitmap(itemList[position])
            holder.binding.txtItem.text = (position + 1).toString()
        }

        override fun getItemCount(): Int {
            return itemList.size
        }

    }


    class ShowAdapter(var context: Context, var itemList: ArrayList<Bitmap>) :
        RecyclerView.Adapter<ShowAdapter.ViewHolder>() {


        inner class ViewHolder(val binding: RecyclerCutterManShowBinding) :
            RecyclerView.ViewHolder(binding.root) {
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder(
                DataBindingUtil.inflate(
                    LayoutInflater.from(context),
                    R.layout.recycler_cutter_man_show,
                    parent,
                    false
                )
            )
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
//            holder.binding.imgItem.setImageBitmap(itemList[position])

            Glide.with(context).load(itemList[position]).into(holder.binding.imgItem)

//            holder.binding.imgItem.background = BitmapDrawable(itemList[position])
        }

        override fun getItemCount(): Int {
            return itemList.size
        }

    }
}












